package com.css.zfzx.sjcj.modules.hddcGeologicalSvyLine.service.impl;

import cn.afterturn.easypoi.excel.ExcelImportUtil;
import cn.afterturn.easypoi.excel.entity.ImportParams;
import cn.afterturn.easypoi.excel.entity.result.ExcelImportResult;

import com.alibaba.fastjson.JSONObject;
import com.css.zfzx.sjcj.common.spacedata.vo.SpaceDataParamsVo;
import com.css.zfzx.sjcj.common.utils.EasyPoiExcelUtil;
import com.css.zfzx.sjcj.common.utils.UpdateUtil;
import com.css.zfzx.sjcj.modules.hddcGeologicalSvyLine.repository.HddcGeologicalsvylineNativeRepository;
import com.css.zfzx.sjcj.modules.hddcGeologicalSvyLine.repository.HddcGeologicalsvylineRepository;
import com.css.zfzx.sjcj.modules.hddcGeologicalSvyLine.repository.entity.HddcGeologicalsvylineEntity;
import com.css.zfzx.sjcj.modules.hddcGeologicalSvyLine.service.HddcGeologicalsvylineService;
import com.css.zfzx.sjcj.modules.hddcGeologicalSvyLine.viewobjects.HddcGeologicalsvylineQueryParams;
import com.css.zfzx.sjcj.modules.hddcGeologicalSvyLine.viewobjects.HddcGeologicalsvylineVO;
import com.css.bpm.platform.api.local.PlatformAPI;
import com.css.bpm.platform.sys.dict.repository.entity.DictItemEntity;
import com.css.bpm.platform.utils.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.util.*;

/**
 * @author lihelei
 * @date 2020-11-27
 */
@Service
public class HddcGeologicalsvylineServiceImpl implements HddcGeologicalsvylineService {

	@Autowired
    private HddcGeologicalsvylineRepository hddcGeologicalsvylineRepository;
    @Autowired
    private HddcGeologicalsvylineNativeRepository hddcGeologicalsvylineNativeRepository;

    @Override
    public JSONObject queryHddcGeologicalsvylines(HddcGeologicalsvylineQueryParams queryParams, int curPage, int pageSize,String sort,String order) {
        Page<HddcGeologicalsvylineEntity> hddcGeologicalsvylinePage = this.hddcGeologicalsvylineNativeRepository.queryHddcGeologicalsvylines(queryParams, curPage, pageSize, sort, order);
        JSONObject jsonObject = PlatformPageUtils.formatPageData(hddcGeologicalsvylinePage);
        return jsonObject;
    }


    @Override
    public HddcGeologicalsvylineEntity getHddcGeologicalsvyline(String id) {
        HddcGeologicalsvylineEntity hddcGeologicalsvyline = this.hddcGeologicalsvylineRepository.findById(id).orElse(null);
         return hddcGeologicalsvyline;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcGeologicalsvylineEntity saveHddcGeologicalsvyline(HddcGeologicalsvylineEntity hddcGeologicalsvyline) {
        String uuid = UUIDGenerator.getUUID();
        hddcGeologicalsvyline.setUuid(uuid);
        hddcGeologicalsvyline.setCreateUser(PlatformSessionUtils.getUserId());
        hddcGeologicalsvyline.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
        hddcGeologicalsvyline.setIsValid("1");
        hddcGeologicalsvyline.setQualityinspectionStatus("0");
        hddcGeologicalsvyline.setExtends10("1");
        this.hddcGeologicalsvylineRepository.save(hddcGeologicalsvyline);
        return hddcGeologicalsvyline;
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public  Iterable<HddcGeologicalsvylineEntity> saveHddcGeologicalsvylineList( List<HddcGeologicalsvylineEntity> list) {
        for (HddcGeologicalsvylineEntity hddcGeologicalsvyline : list) {
            String uuid = UUIDGenerator.getUUID();
            hddcGeologicalsvyline.setUuid(uuid);
            hddcGeologicalsvyline.setCreateUser(PlatformSessionUtils.getUserId());
            hddcGeologicalsvyline.setCreateTime(PlatformDateUtils.getCurrentTimestamp());
            hddcGeologicalsvyline.setIsValid("1");
            hddcGeologicalsvyline.setQualityinspectionStatus("0");
            hddcGeologicalsvyline.setExtends10("1");
        }
        return hddcGeologicalsvylineNativeRepository.batchSave(list);
    }
    @Override
    @Transactional(rollbackFor = Exception.class)
    public HddcGeologicalsvylineEntity updateHddcGeologicalsvyline(HddcGeologicalsvylineEntity hddcGeologicalsvyline) {
        HddcGeologicalsvylineEntity entity = hddcGeologicalsvylineRepository.findById(hddcGeologicalsvyline.getUuid()).get();
        UpdateUtil.copyNullProperties(entity,hddcGeologicalsvyline);
        hddcGeologicalsvyline.setUpdateUser(PlatformSessionUtils.getUserId());
        hddcGeologicalsvyline.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
        this.hddcGeologicalsvylineRepository.save(hddcGeologicalsvyline);
        return hddcGeologicalsvyline;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteHddcGeologicalsvylines(List<String> ids) {
        List<HddcGeologicalsvylineEntity> hddcGeologicalsvylineList = this.hddcGeologicalsvylineRepository.findAllById(ids);
        if(!PlatformObjectUtils.isEmpty(hddcGeologicalsvylineList) && hddcGeologicalsvylineList.size() > 0) {
            for(HddcGeologicalsvylineEntity hddcGeologicalsvyline : hddcGeologicalsvylineList) {
                hddcGeologicalsvyline.setIsValid("0");
                hddcGeologicalsvyline.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcGeologicalsvyline.setUpdateTime(new Date());
                this.hddcGeologicalsvylineRepository.save(hddcGeologicalsvyline);
            }
        }
    }

    @Override
    public List<DictItemEntity> getValidDictItemsByDictCode(String dictCode) {
        List<DictItemEntity> validDictItems = PlatformAPI.getDictAPI().getValidDictItemsByDictCode(dictCode);
        return validDictItems;
    }

    @Override
    public void exportFile(HddcGeologicalsvylineQueryParams queryParams, HttpServletResponse response) {
        List<HddcGeologicalsvylineEntity> yhDisasterEntities = hddcGeologicalsvylineNativeRepository.exportYhDisasters(queryParams);
        List<HddcGeologicalsvylineVO> list=new ArrayList<>();
        for (HddcGeologicalsvylineEntity entity:yhDisasterEntities) {
            HddcGeologicalsvylineVO yhDisasterVO=new HddcGeologicalsvylineVO();
            BeanUtils.copyProperties(entity,yhDisasterVO);
            list.add(yhDisasterVO);
        }
        EasyPoiExcelUtil.exportExcel(list, "地质调查路线-线", "地质调查路线-线", HddcGeologicalsvylineVO.class, "地质调查路线-线.xls", response);
    }

    @Override
    public String exportExcel(MultipartFile file, HttpServletResponse response) {
        try {
            // 返回的消息
            StringBuilder returnMsg = new StringBuilder();
            // 导入的参数信息
            ImportParams params = new ImportParams();
            // 设置简析的第一行
            params.setHeadRows(1);
            // 是否需要校验
            params.setNeedVerify(true);
            // 获取到Excel数据
            ExcelImportResult<HddcGeologicalsvylineVO> result = ExcelImportUtil.importExcelMore(file.getInputStream(), HddcGeologicalsvylineVO.class, params);
            List<HddcGeologicalsvylineVO> list = result.getList();
            // Excel条数据
            int firstList = list.size();
            StringBuilder sb = new StringBuilder();
            //保存
            saveDisasterList(list, sb);
            returnMsg.append("成功导入" + (result.getList().size() ));
            returnMsg.append(sb);
            if (result.isVerifyFail()) {
                // 校验返回失败行信息
                Iterator<HddcGeologicalsvylineVO> iterator = result.getFailList().iterator();
                while (iterator.hasNext()) {
                    HddcGeologicalsvylineVO yhDisasterVO = iterator.next();
                    String error = "";
                    returnMsg.append("第" + yhDisasterVO.getRowNum() + "行" + yhDisasterVO.getErrorMsg() + "<br/>");
                    returnMsg.append(error);
                }
            }
            return returnMsg.toString();
        } catch (Exception e) {

            return "导入失败，请检查数据正确性";
        }
    }
    /**
     * 批量存入库表并且返回错误数量
     *
     * @param list
     * @param message
     * @return
     */
    public void saveDisasterList( List<HddcGeologicalsvylineVO> list, StringBuilder message) {
        for (int i = 0; i < list.size(); i++) {
            HddcGeologicalsvylineEntity yhDisasterEntity = new HddcGeologicalsvylineEntity();
            HddcGeologicalsvylineVO yhDisasterVO = list.get(i);
            // 将VO数据映射拷贝到库表中
            BeanUtils.copyProperties(yhDisasterVO, yhDisasterEntity);
            saveHddcGeologicalsvyline(yhDisasterEntity);
        }
    }

    /**
     * 逻辑删除-根据项目id删除数据
     * @param projectIds
     */
    @Override
    public void deleteByProjectId(List<String> projectIds) {
        List<HddcGeologicalsvylineEntity> hddcGeologicalsvylineList = this.hddcGeologicalsvylineRepository.queryHddcGeologicalsvylinesByProjectId(projectIds);
        if(!PlatformObjectUtils.isEmpty(hddcGeologicalsvylineList) && hddcGeologicalsvylineList.size() > 0) {
            for(HddcGeologicalsvylineEntity hddcGeologicalsvyline : hddcGeologicalsvylineList) {
                hddcGeologicalsvyline.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcGeologicalsvyline.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcGeologicalsvyline.setIsValid("0");
                this.hddcGeologicalsvylineRepository.save(hddcGeologicalsvyline);
            }
        }
    }

    /**
     * 逻辑删除-根据任务id删除数据
     * @param taskIds
     */
    @Override
    public void deleteByTaskId(List<String> taskIds) {
        List<HddcGeologicalsvylineEntity> hddcGeologicalsvylineList = this.hddcGeologicalsvylineRepository.queryHddcGeologicalsvylinesByTaskId(taskIds);
        if(!PlatformObjectUtils.isEmpty(hddcGeologicalsvylineList) && hddcGeologicalsvylineList.size() > 0) {
            for(HddcGeologicalsvylineEntity hddcGeologicalsvyline : hddcGeologicalsvylineList) {
                hddcGeologicalsvyline.setUpdateUser(PlatformSessionUtils.getUserId());
                hddcGeologicalsvyline.setUpdateTime(PlatformDateUtils.getCurrentTimestamp());
                hddcGeologicalsvyline.setIsValid("0");
                this.hddcGeologicalsvylineRepository.save(hddcGeologicalsvyline);
            }
        }

    }

    @Override
    public List<HddcGeologicalsvylineEntity> findAll() {
        List<HddcGeologicalsvylineEntity> list=this.hddcGeologicalsvylineRepository.findAll();
        return list;
    }

    @Override
    @Transactional
    public void deleteFileData(SpaceDataParamsVo paramsVo) {
        String provinceName=paramsVo.getProvinceName();
        String cityName=paramsVo.getCityName();
        String areaName=paramsVo.getAreaName();
        String savefilename=paramsVo.getSavefilename();

        hddcGeologicalsvylineRepository.deleteFileData(provinceName,cityName,areaName,savefilename);
    }

    @Override
    public String judegeParams(String[] datas) {
        String str = "";
        Set<String> set = new HashSet<String>(Arrays.asList(datas));
        if(!set.contains("ID")){
            str+="ID,";
        }
        if(!set.contains("FieldID")){
            str+="FieldID,";
        }
        if(!set.contains("SvyLineName")){
            str+="SvyLineName,";
        }
        if(!set.contains("Purpose")){
            str+="Purpose,";
        }
        if(!set.contains("CommentInfo")){
            str+="CommentInfo,";
        }
        return str;
    }

    @Override
    public void savehddcGeologicalsvylineServiceFromShpFiles(List<List<Object>> list, String provinceName, String cityName, String areaName,String savefilename) {
        if(list!=null&&list.size()>0){
            List<HddcGeologicalsvylineEntity> datas= new ArrayList<>();
            for(int i=0;i<list.size();i++){
                List<Object> obs=list.get(i);
                HddcGeologicalsvylineEntity data = new HddcGeologicalsvylineEntity();
                data.setArea(areaName);
                data.setProvince(provinceName);
                data.setCity(cityName);
                data.setExtends8(savefilename);
                data.setId(obs.get(1).toString());
                data.setFieldid(obs.get(2).toString());
                data.setSvylinename(obs.get(3).toString());
                data.setPurpose(obs.get(4).toString());
                data.setCommentInfo(obs.get(5).toString());
                String pstr=obs.get(0).toString();
                data.setExtends16("CGCS2000");
                /*String[] ss1=pstr.split("\\(");
                if(ss1.length>=2){
                    String[] ss2=ss1[ss1.length-1].split("\\)");
                    if(ss2.length<=2){
                        String spacedata=ss2[0].replace(",",";").replace("; ",";").replace(" ",",");
                        data.setExtends5(spacedata);
                    }
                }*/
                pstr = pstr.replace(")), ((", "#");
                pstr = pstr.replace("), (", "#");
                String[] ss1=pstr.split("\\(");
                if(ss1.length>=2){
                    String[] ss2=ss1[ss1.length-1].split("\\)");
                    if(ss2.length<=2){
                        String spacedata=ss2[0].replace(",",";").replace("; ",";").replace(" ",",");
                        data.setExtends5(spacedata);
                    }
                }
                datas.add(data);
            }
            deleteByCreateUser(provinceName,cityName,areaName);
            saveHddcGeologicalsvylineList(datas);
        }
    }

    public void deleteByCreateUser(String provinceName, String cityName, String areaName){
        String createID=PlatformSessionUtils.getUserId();
        List<HddcGeologicalsvylineEntity> hddcGeologicalsvyplanninglineList = this.hddcGeologicalsvylineRepository.queryHddcGeologicalsvyplanninglinesByCreateuser(createID,provinceName,cityName,areaName);
        if(!PlatformObjectUtils.isEmpty(hddcGeologicalsvyplanninglineList) && hddcGeologicalsvyplanninglineList.size() > 0) {
            hddcGeologicalsvylineRepository.deleteAll(hddcGeologicalsvyplanninglineList);
        }
    }

}
